package example.borrow;


import example.entity.Borrow;
import example.entity.User;
import example.service.BorrowService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;

/**
 * 添加借阅记录
 *
 * @author 张心怡
 * @date 2024/12/16
 */
@WebServlet("/addBorrowServlet")
public class AddBorrowServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        User userId = (User) request.getSession().getAttribute("user");
        int bookId = Integer.parseInt(request.getParameter("bookId"));
        try {
            // 获取当前日期
            Date today = new Date();
            // 使用Calendar类来进行日期的计算操作
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(today);
            calendar.add(Calendar.DAY_OF_MONTH, 15);
            // 获取计算后的日期
            Date after15Days = calendar.getTime();

            Borrow record = new Borrow();
            record.setUserId(userId.getId());
            record.setBookId(bookId);
            record.setBorrowDate(today);
            record.setDueDate(after15Days);

            BorrowService.addBorrow(record);

            response.sendRedirect("listBorrowsServlet");
        } catch (Exception e) {
            e.printStackTrace();
            // 可以根据实际情况给前端返回更友好的错误提示，比如设置错误信息到请求属性，转发到错误页面等
        }
    }
}
